using System;
using System.Collections;
using UnityEngine;

/*
权限需要主动加到AndroidManifest.xml，Unity不会自动加
<uses-permission android:name="android.permission.RECORD_AUDIO" />
 */
namespace CGF
{
    public class AudioRecorder : MonoBehaviour
    {
        private static AudioRecorder _instance;

        public static AudioRecorder Instance
        {
            get
            {
                if (!_instance)
                {
                    _instance = FindObjectOfType<AudioRecorder>();
                    if (!_instance)
                    {
                        GameObject go = new GameObject(nameof(AudioRecorder));
                        DontDestroyOnLoad(go);
                        _instance = go.AddComponent<AudioRecorder>();
                    }
                }

                return _instance;
            }
        }

        private AudioClip recordClip;
        private string microphoneDevice;
        private Action<AudioClip> callback;

        public void StartRecord(Action<AudioClip> callback)
        {
            this.callback = callback;
            StartCoroutine(_StartRecord());
        }

        private IEnumerator _StartRecord()
        {
            if (!Application.HasUserAuthorization(UserAuthorization.Microphone))
            {
                yield return Application.RequestUserAuthorization(UserAuthorization.Microphone);
                callback?.Invoke(null);
                yield break;
            }

#if !UNITY_WEBGL
            if (Microphone.devices.Length == 0)
            {
                callback?.Invoke(null);
                yield break;
            }

            microphoneDevice = Microphone.devices[0];
            recordClip = Microphone.Start(microphoneDevice, false, 10, 16000);
#endif
        }

        public void StopRecord()
        {
#if !UNITY_WEBGL
            if (Microphone.GetPosition(microphoneDevice) > 0)
            {
                Microphone.End(microphoneDevice);
                callback?.Invoke(recordClip);
            }
            else
            {
                callback?.Invoke(null);
            }
#endif
        }
    }
}
